import 'package:dio/dio.dart';

import '../../../generated/json/base/json_convert_content.dart';
import '../../../https/index.dart';
import '../../config/index.dart';
import '../index.dart';

abstract class BaseSingleViewModel<T> extends BaseViewModel {
  late T _data;

  T get data => _data;

  RequestConfig get requestConfig => setRequestConfig();

  @override
  Future<void> initData() async {
    if (await checkNet()) {
      setNoNet(message: "没有网络");
      notifyListeners();
      return;
    }
    try {
      final ResponseModel responseModel = await loadData();
      final T? modelForT = JsonConvert.fromJsonAsT<T>(responseModel.data);
      if (modelForT == null) {
        /// 一般不会出现转换错误
        setOther("数据转换错误");
      } else {
        _data = modelForT;
        onComplete(_data);
      }
      notifyListeners();
    } catch (e) {
      if (e is DioException) {
        if (e is DioUnAuthorizedError) {
        } else {
          setResponseError(message: e.message ?? "系统错误～");
        }
      } else {
        /// 这里出现问题 一般就是代码问题 请自查
        setOther(e.toString());
      }
      notifyListeners();
    }
  }

  /// 需要重写这个方法来调用sendRequest来获取数据
  Future<ResponseModel> loadData() async {
    return await sendRequest(requestConfig);
  }

  /// 数据获取之后做的处理 ～
  void onComplete(T data) {}

  /// 初始化request config
  RequestConfig setRequestConfig();
}
